package com.hcyy.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hcyy.entity.BaseProperty;
import com.hcyy.entity.Cart;
import com.hcyy.entity.CustOrder;
import com.hcyy.entity.CustOrderLog;
import com.hcyy.entity.Message;
import com.hcyy.entity.Product;
import com.hcyy.entity.User;
import com.hcyy.interceptor.Token;
import com.hcyy.service.CartService;
import com.hcyy.service.CustOrderLogService;
import com.hcyy.service.CustOrderService;
import com.hcyy.service.ProductService;
import com.hcyy.util.UserUtil;

@Controller
@RequestMapping("/Shop")
public class OrderController {
	@Autowired
	private CustOrderService custOrderService;
	@Autowired
	private CustOrderLogService custOrderLogService;
	@Autowired
	private ProductService productService;
	@Autowired
	private CartService cartService;
	@Autowired
	private UserUtil userUtil;
	@RequestMapping(value="/Order/GetAddressInfo",method=RequestMethod.POST)
	@ResponseBody
	public User getUserAddressInfo(HttpServletRequest request){
		User user=userUtil.findUser(request);
		return user;
	}

	/*@RequestMapping("/GoOrder/Index")
	public String goOrder(@RequestParam("idarray")  String[] idarray,Model model,HttpServletRequest request){
		try {
			custOrderService.addOrder(idarray, request, model);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "pay";
	}*/

	@Token(remove=true)
	@RequestMapping(value="/GoOrder/Index",method=RequestMethod.POST)
	@ResponseBody
	public CustOrder goOrder(@RequestBody Map<String,Object> map,Model model,HttpServletRequest request){
		try {
			return custOrderService.addOrder(map, model,request);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@RequestMapping("/Pay")
	public String toPay(String sid,Model model,HttpServletRequest request){
		User user=userUtil.findUser(request);
		String userid=user.getDwbh();
		CustOrder custOrder=custOrderService.findOrderBySid(sid,userid);
		model.addAttribute("custOrder",custOrder);
		model.addAttribute("user",user);
		model.addAttribute("sid",sid);
		return "pay";
	}

	@RequestMapping("/OrderList")
	public String findOrderList(String orderstatus,Model model,HttpServletRequest request){
		String dwbh=userUtil.findUser(request).getDwbh();
		Integer sjid=(Integer) request.getSession().getAttribute("sjid");
		List<CustOrder> orderList=custOrderService.findOrderByDwbh(orderstatus, dwbh,sjid);
		model.addAttribute("orderList",orderList);
		return "orderlist";
	}

	@RequestMapping("/CancelOrder")
	@ResponseBody
	public Message cancelOrder(HttpServletRequest request){
		String dwbh=userUtil.findUser(request).getDwbh();
		String sid=request.getParameter("sid");
		int i=custOrderService.cancelOrderBySid(sid, dwbh);
		Message message=new Message();
		if(i>0){
			message.setMsg("取消订单成功！");
			return message;
		}
		return message;
	}
	
	@Token(save=true)
	@RequestMapping(value="/QuickOrder",method={RequestMethod.POST,RequestMethod.GET})
	public String quickOrder(String[] spidarray,String[] numarray,Model model,HttpServletRequest request){
		Integer sjid=(Integer) request.getSession().getAttribute("sjid");
		if(spidarray==null||numarray==null){
			return "redirect:/Shop/User?sjid="+sjid;
		}
		String dwbh=userUtil.findUser(request).getDwbh();
		List<Product> productlist=new ArrayList<Product>();
		//加入购物车
		for(int i=0;i<spidarray.length;i++){
			Product product=productService.findProductById(spidarray[i],sjid);
			product.setNum(Integer.parseInt(numarray[i]));
			int fQty=product.getNum();
			double newPrice=judgePrice(fQty,product);//根据下单商品的数量更新价格
			product.setPrice(newPrice);
			productlist.add(product);
			//快速下单的同时加入购物车
			Cart cart = new Cart();
			cart.setDwbh(dwbh);
			cart.setFPrice(newPrice);
			cart.setFQty(fQty);
			cart.setPihao(product.getProductBal().get(0).getPihao());
			cart.setSjid(product.getSjid());
			cart.setSpid(product.getSpid());
			cart.setSpmch(product.getSpmch());
			cart.setZhongbz(product.getZhongbz());
			cartService.addCart(cart);
		}
		model.addAttribute("productlist",productlist);
		return "quickorder";
	}
	private double judgePrice(int FQty, BaseProperty bp) {
		int jlgg=bp.getJlgg();//商品件装量
		Double newpriceChl=bp.getPriceChl();//查询商品的最新价格（拆零价）
		Double newpriceZhj=bp.getPriceZhj();//查询商品的最新价格（整件价）
		double newPrice=newpriceZhj;
		if(newpriceChl!=0&&FQty<jlgg){//数量小于件装量，该商品有拆零价
			newPrice=newpriceChl;
		}
		return newPrice;
	}
	@Token(remove=true)
	@RequestMapping(value="/GoQuickOrder/Index",method=RequestMethod.POST)
	@ResponseBody
	public CustOrder goQuickOrder(@RequestBody Map<String,Object> map,Model model,HttpServletRequest request){
		try {
			return custOrderService.addQuickOrder(map, model,request);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	//修改订单
	@ResponseBody
	@RequestMapping(value="/ModOrder",method=RequestMethod.POST,produces = "text/plain; charset=utf-8")
	public String modifyOrder(HttpServletRequest request){
		String sid=request.getParameter("sid");//订单号
		int FQty=Integer.parseInt(request.getParameter("FQty"));//总数量
		double FAmount=Double.parseDouble(request.getParameter("FAmount"));//总金额
		String spidarray=request.getParameter("spidarray");
		String numarray=request.getParameter("numarray");
		String[] spids=spidarray.split(",");
		String[] nums=numarray.split(",");
		Integer sjid=(Integer) request.getSession().getAttribute("sjid");
		String msg="";
		try {
			msg= custOrderService.modifyOrder(sid, FQty, FAmount, spids, nums,sjid);
		} catch (Exception e) {
			e.printStackTrace();
			msg="订单修改出现异常！";
		}
		return msg;
	}
	
	@ResponseBody
	@RequestMapping(value="/Log",method=RequestMethod.POST)
	public List<CustOrderLog> loadLog(HttpServletRequest request){
		String sid=request.getParameter("sid");
		List<CustOrderLog> logs=custOrderLogService.findOrderLogBySid(sid);
		return logs;
	}
}
